<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { logger } from '../utils/logger'
import { wsManager } from '../utils/websocket'

// 获取当前时间
const currentTime = ref('')

// 更新时间的函数
const updateTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  currentTime.value = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

// 按钮状态
const buttonStates = ref({
  home: 'normal',
  user: 'normal',
  dataImport: 'normal',
  dataManage: 'normal',
  dataAnnotation: 'normal',
  trainManage: 'normal',
  abilityAssess: 'normal',
  modelInference: 'normal',
  dataManage: 'normal',
  settings: 'normal',
  login: 'normal'
})

// 鼠标事件处理
const handleMouseEnter = (button) => {
  buttonStates.value[button] = 'hover'
}

const handleMouseLeave = (button) => {
  buttonStates.value[button] = 'normal'
}

const handleMouseDown = (button) => {
  buttonStates.value[button] = 'click'
}

const handleMouseUp = async (button) => {
  buttonStates.value[button] = 'hover'
  
  // 获取功能域对应的编号
  let destination = 0
  if (button === 'dataAnnotation') {
    destination = 1
  } else if (button === 'trainManage') {
    destination = 2
  } else if (button === 'abilityAssess') {
    destination = 3
  } else if (button === 'modelInference') {
    destination = 4
  } else if (button === 'dataManage') {
    destination = 5
  } else if (button === 'login') {
    openLoginDialog()
    return
  } else {
    return
  }

  try {
    // 构建跳转请求
    const requestData = {
      requestID: Date.now().toString(), 
      operation: 'user_jump',
      uid: localStorage.getItem('username') || '',
      params: { destination },
      authToken: localStorage.getItem('authToken') || ''
    }
    // console.log("authtoken", localStorage.getItem('authToken'))
    // console.log("token", requestData.authToken)
    console.log("requestData", requestData)
    // 发送跳转请求
    // const response = await wsManager.sendMessage(requestData)
    const response = {
    requestID:Date.now().toString(),
    operation:"user_jump",
    uid:localStorage.getItem('username') || '',
    params:{ destination },
    status: 1
}
    console.log("response", response)
    console.log("1", 2)
    // 根据返回状态处理跳转
    if (response.status === 1) {

      // 允许跳转
      if (button === 'dataAnnotation') {
        router.push('/data-annotation')
      } else if (button === 'trainManage') {
        router.push('/model-training')
      } else if (button === 'abilityAssess') {
        router.push('/ability-access')
      } else if (button === 'modelInference') {
        router.push('/inference-demo')
      } else if (button === 'dataManage') {
        router.push('/data-management')
      }
    } else if (response.status === 0) {
      // 需要登录
      alert('身份认证过期，请重新登录')
      router.push('/')
      openLoginDialog()
    } else if (response.status === 2) {
      // 权限不足
      alert('权限不足，无法访问该功能')
    } else {
      // 错误码
      alert(`发生错误，错误码：${response.status}`)
    }
  } catch (error) {
    console.error('跳转请求失败:', error)
    // alert('跳转请求失败，请稍后重试')
  }
  
}

// 路由
const router = useRouter()

// 登录弹窗显示状态
const showLoginDialog = ref(false)
// 注册弹窗显示状态
const showRegisterDialog = ref(false)

// 用户登录信息
const loginForm = reactive({
  username: '',
  password: '',
  rememberPassword: false
})

// 用户注册信息
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  role: '访客',
  isProfessional: false
})

// 错误信息
const errorMessage = ref('')
// 注册错误信息
const registerErrorMessage = ref('')

// 打开登录弹窗
const openLoginDialog = () => {
  logger.clearLogs()
  showLoginDialog.value = true
  errorMessage.value = ''
  loginForm.username = ''
  loginForm.password = ''
}

// 关闭登录弹窗
const closeLoginDialog = () => {
  showLoginDialog.value = false
}

// 打开注册弹窗
const openRegisterDialog = () => {
  showLoginDialog.value = false
  showRegisterDialog.value = true
  registerErrorMessage.value = ''
  registerForm.username = ''
  registerForm.password = ''
  registerForm.confirmPassword = ''
  registerForm.role = '访客'
  registerForm.isProfessional = false
}

// 关闭注册弹窗
const closeRegisterDialog = () => {
  showRegisterDialog.value = false
}

// 登录处理
const handleLogin = async () => {
  try {
    // 构建请求数据
    const requestData = {
      requestID: Date.now().toString(),
      operation: 'user_login',
      uid: loginForm.username,
      params: {
        id: loginForm.username,
        password: loginForm.password
      }
    }

    // 记录请求日志
    await logger.logRequest({
      operation: 'user_login',
      url: 'login',
      method: 'POST',
      data: requestData
    })

    console.log(logger.getStoredLogs(requestData.operation))
    // 使用全局wsManager发送登录请求
    const response = await wsManager.sendMessage(requestData)

    // 记录响应日志
    await logger.logResponse({
      status: response.status,
      data: response
    })

    console.log(logger.getStoredLogs(response.operation))

    // 处理响应
    if (response.status === 1) {
      // 登录成功
      closeLoginDialog()
      // 保存用户名和token到localStorage
      localStorage.setItem("username", loginForm.username)
      localStorage.setItem("authToken", response.authToken)
    } else {
      // 登录失败
      errorMessage.value = '密码错误，请重新输入！'
    }
  } catch (error) {
    await logger.logError(error)
    console.error('登录请求失败:', error)
    errorMessage.value = '登录请求失败，请稍后重试！'
  }
}

// 打开注册页面
const handleRegister = () => {
  openRegisterDialog()
}

// 提交注册
const submitRegister = async () => {
  // 验证密码是否一致
  if (registerForm.password !== registerForm.confirmPassword) {
    registerErrorMessage.value = '两次输入的密码不一致！'
    return
  }
  
  try {
    // 构建请求数据
    const requestData = {
      requestID: Date.now().toString(),
      operation: 'user_register',
      uid: registerForm.username,
      params: {
        id: registerForm.username,
        password: registerForm.password,
        password2: registerForm.confirmPassword,
        type: registerForm.role === '数据管理员' ? 1 : (registerForm.role === '深度学习管理员' ? 2 : 3)
      }
    }
    
    // 记录请求日志
    await logger.logRequest({
      url: '/auth/register',
      method: 'POST',
      data: requestData
    })
    console.log(logger.getStoredLogs(requestData.operation))
    // 发送注册请求
    const response = await wsManager.sendMessage(requestData)
    
    // 记录响应日志
    await logger.logResponse({
      status: response.data.status,
      data: response.data
    })
    console.log(logger.getStoredLogs(response.operation))
    // 处理响应
    if (response.data.status === '200') {
      // 注册成功，切换到登录页面并自动填充用户名
      showRegisterDialog.value = false
      showLoginDialog.value = true
      loginForm.username = registerForm.username
      loginForm.password = ''
      errorMessage.value = '注册成功，请登录！'
    } else {
      // 注册失败
      registerErrorMessage.value = '注册失败，请稍后重试！'
    }
  } catch (error) {
    await logger.logError(error)
    console.error('注册请求失败:', error)
    registerErrorMessage.value = '注册请求失败，请稍后重试！'
  }
}

// 更新时间
onMounted(() => {
  updateTime()
  // 每秒更新一次时间
  setInterval(updateTime, 1000)
})
</script>

<template>
  <div class="main-container">
    <!-- 主界面 -->
    <div class="main-interface">
      <!-- 主要内容区域 -->
      <div class="main-content">
        <div class="background-image">
          <img src="/pic/3个模块背景.jpg" alt="背景图" class="bg-img">
          
          <!-- 顶部栏 - 移动到蓝色装饰条位置 -->
          <div class="top-bar">
            <!-- Logo和系统名称 -->
            <div class="logo-container">
              <img src="/pic/LOGO.png" alt="Logo" class="logo-img">
              <span class="system-name">算筹平台系统</span>
            </div>
            
            <!-- 右侧按钮 -->
            <div class="right-buttons">
              <!-- 设置按钮 -->
              <!--<div class="setting-button button"
                   @mouseenter="handleMouseEnter('settings')"
                   @mouseleave="handleMouseLeave('settings')"
                   @mousedown="handleMouseDown('settings')"
                   @mouseup="handleMouseUp('settings')">
                <img :src="buttonStates.login === 'hover' ? '/pic/设置-悬浮.png' : buttonStates.login === 'click' ? '/pic/设置-点击.png' : '/pic/设置-正常.png'" alt="设置">

              </div>-->
              
              <!-- 登录按钮 -->
              <div class="login-button button"
                   @mouseenter="handleMouseEnter('login')"
                   @mouseleave="handleMouseLeave('login')"
                   @mousedown="handleMouseDown('login')"
                   @mouseup="handleMouseUp('login')">
                <img :src="buttonStates.login === 'hover' ? '/pic/立即登录-悬浮.png' : buttonStates.login === 'click' ? '/pic/立即登录-点击.png' : '/pic/立即登录-正常.png'" alt="立即登录">
                <!-- <img src="/pic/立即登录-正常.png" alt="立即登录"> -->
              </div>
            </div>
          </div>
      
          <!-- 5个主要按钮 -->
          <div class="main-buttons">
            <!-- 数据管理按钮 -->
            <div class="data-manage-button main-button"
                 @mouseenter="handleMouseEnter('dataManage')"
                 @mouseleave="handleMouseLeave('dataManage')"
                 @mousedown="handleMouseDown('dataManage')"
                 @mouseup="handleMouseUp('dataManage')">
              <img :src="buttonStates.dataManage === 'hover' ? '/pic/数据管理-悬浮.png' : buttonStates.dataManage === 'click' ? '/pic/数据管理-点击.png' : '/pic/数据管理-正常.png'" alt="数据管理">
              <span>数据管理</span>
            </div>
            <!-- 数据标注按钮 -->
            <div class="data-annotation-button main-button"
                 @mouseenter="handleMouseEnter('dataAnnotation')"
                 @mouseleave="handleMouseLeave('dataAnnotation')"
                 @mousedown="handleMouseDown('dataAnnotation')"
                 @mouseup="handleMouseUp('dataAnnotation')">
              <img :src="buttonStates.dataAnnotation === 'hover' ? '/pic/数据标注-悬浮.png' : buttonStates.dataAnnotation === 'click' ? '/pic/数据标注-点击.png' : '/pic/数据标注-正常.png'" alt="数据标注">
              <span>数据标注</span>
            </div>

            <!-- 训练管理按钮 -->
            <div class="train-manage-button main-button"
                 @mouseenter="handleMouseEnter('trainManage')"
                 @mouseleave="handleMouseLeave('trainManage')"
                 @mousedown="handleMouseDown('trainManage')"
                 @mouseup="handleMouseUp('trainManage')">
                 <img :src="buttonStates.trainManage === 'hover' ? '/pic/模型训练-悬浮.png' : buttonStates.trainManage === 'click' ? '/pic/模型训练-点击.png' : '/pic/模型训练-正常.png'" alt="模型训练">
                 <span>模型训练</span>
            </div>

              <!-- 模型推理按钮 -->
              <div class="model-inference-button main-button"
                 @mouseenter="handleMouseEnter('modelInference')"
                 @mouseleave="handleMouseLeave('modelInference')"
                 @mousedown="handleMouseDown('modelInference')"
                 @mouseup="handleMouseUp('modelInference')">
              <img :src="buttonStates.modelInference === 'hover' ? '/pic/模型推理-悬浮.png' : buttonStates.modelInference === 'click' ? '/pic/模型推理-点击.png' : '/pic/模型推理-正常.png'" alt="模型推理">
              <span>模型推理</span>
            </div>
            
            
            
            <!-- 能力评估按钮 -->
            <div class="ability-assess-button main-button"
                 @mouseenter="handleMouseEnter('abilityAssess')"
                 @mouseleave="handleMouseLeave('abilityAssess')"
                 @mousedown="handleMouseDown('abilityAssess')"
                 @mouseup="handleMouseUp('abilityAssess')">
                 <img :src="buttonStates.abilityAssess === 'hover' ? '/pic/能力评估-悬浮.png' : buttonStates.abilityAssess === 'click' ? '/pic/能力评估-点击.png' : '/pic/能力评估-正常.png'" alt="能力评估">
                 <span>能力评估</span>
            </div>
          </div>
          

        </div>
      </div>
    </div>
  </div>
  
  <!-- 登录弹窗 -->
  <div class="login-dialog" v-if="showLoginDialog">
    <div class="dialog-content">
      <div class="dialog-header">
        <span>登录</span>
        <span class="close-button" @click="closeLoginDialog">×</span>
      </div>
      
      <div class="dialog-body">
        <!-- 用户ID输入框 -->
        <div class="input-group">
          <div class="input-icon">
            <img src="/pic/register/ID.png" alt="ID">
          </div>
          <input type="text" v-model="loginForm.username" placeholder="请输入ID">
        </div>
        
        <!-- 密码输入框 -->
        <div class="input-group">
          <div class="input-icon">
            <img src="/pic/register/密码.png" alt="密码">
          </div>
          <input type="password" v-model="loginForm.password" placeholder="••••••••••">
        </div>
        
        <!-- 错误提示 -->
        <div class="error-message" v-if="errorMessage">
          {{ errorMessage }}
        </div>
        
        <!-- 记住密码 -->
        <div class="remember-password">
          <input type="checkbox" id="remember" v-model="loginForm.rememberPassword">
          <label for="remember">记住密码</label>
          
          <div class="register-button">
            <button @click="handleRegister">注册</button>
          </div>
        </div>
        
        <!-- 登录按钮 -->
        <div class="login-button-container">
          <button @click="handleLogin">登录</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 注册弹窗 -->
  <div class="register-dialog" v-if="showRegisterDialog">
    <div class="dialog-content">
      <div class="dialog-header">
        <span>注册</span>
        <span class="close-button" @click="closeRegisterDialog">×</span>
      </div>
      
      <div class="dialog-body">
        <!-- 用户ID输入框 -->
        <div class="input-group">
          <div class="input-icon">
            <img src="/pic/register/ID.png" alt="ID">
          </div>
          <input type="text" v-model="registerForm.username" placeholder="请输入ID">
        </div>
        
        <!-- 密码输入框 -->
        <div class="input-group">
          <div class="input-icon">
            <img src="/pic/register/密码.png" alt="密码">
          </div>
          <input type="password" v-model="registerForm.password" placeholder="请输入密码">
        </div>
        
        <!-- 确认密码输入框 -->
        <div class="input-group">
          <div class="input-icon">
            <img src="/pic/register/密码.png" alt="确认密码">
          </div>
          <input type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码">
        </div>
        
        <!-- 角色偏好下拉框 -->
        <div class="input-group">
          <select v-model="registerForm.role" class="role-select">
            <option value="访客">访客</option>
            <option value="数据标注员">数据标注员</option>
            <option value="数据管理员">数据管理员</option>
            <option value="深度学习管理员">深度学习管理员</option>
          </select>
        </div>
        
        <!-- 错误提示 -->
        <div class="error-message" v-if="registerErrorMessage">
          {{ registerErrorMessage }}
        </div>
        
        <!-- 专业用户勾选 -->
        <div class="professional-user">
          <input type="checkbox" id="professional" v-model="registerForm.isProfessional">
          <label for="professional">我是专业用户</label>
        </div>
        
        <!-- 按钮组 -->
        <div class="button-group">
          <button class="cancel-button" @click="closeRegisterDialog">取消</button>
          <button class="register-submit-button" @click="submitRegister">注册</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.main-container {
  width: 100%;
  height: 100vh;
  position: relative;
  background-color: #f0f2f5;
  overflow: hidden;
}

.main-interface {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.top-bar {
  height: auto;
  background-color: transparent;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  color: white;
  position: absolute;
  top: 25%;
  left: 19%;
  width: 60%;
  z-index: 10;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 3%;
  width: 50%;
}

.logo-img {
  width: 80px;
  height: 80px;
}

.system-name {
  font-size: 40px;
  font-weight: bold;
  
}

.right-buttons {
  display: flex;
  align-items: center;
}

.button {
  margin-left: 15px;
  cursor: pointer;
}

.main-content {
  flex: 1;
  position: relative;
}

.background-image {
  width: 100%;
  height: 100%;
  position: relative;
}

.bg-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.main-buttons {
  position: absolute;
  top: 57%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  gap: 6%;
}

.main-button {
  cursor: pointer;
  transform: scale(1.275); /* 放大1.5倍 */
  transition: transform 0.2s ease;
}

.quick-task-button {
  position: absolute;
  bottom: 23%;
  right: 20%;
}

.quick-task-button button {
  background-color: #4a6baf;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

/* 登录弹窗样式 */
.login-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  width: 400px;
  border-radius: 8px;
  overflow: hidden;
}

.dialog-header {
  background-color: #4a6baf;
  color: white;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-button {
  cursor: pointer;
  font-size: 20px;
}

.dialog-body {
  padding: 20px;
}

.input-group {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 15px;
  overflow: hidden;
}

.input-icon {
  padding: 10px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-icon img {
  width: 20px;
  height: 20px;
}

input[type="text"],
input[type="password"] {
  flex: 1;
  padding: 10px;
  border: none;
  outline: none;
}

.error-message {
  color: red;
  margin-bottom: 15px;
  font-size: 14px;
}

.remember-password {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.register-button button {
  background-color: transparent;
  border: 1px solid #4a6baf;
  color: #4a6baf;
  padding: 5px 15px;
  border-radius: 4px;
  cursor: pointer;
}

.login-button-container button {
  width: 100%;
  background-color: #4a6baf;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

/* 注册弹窗样式 */
.register-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.role-select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  background-color: white;
}

.professional-user {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.professional-user label {
  margin-left: 8px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.cancel-button {
  flex: 1;
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.register-submit-button {
  flex: 1;
  background-color: #4a6baf;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}
.data-annotation-button {
  position: relative;
}

.main-buttons span {
  position: absolute;
  bottom: 27%;
  left: 0;
  right: 0;
  text-align: center;
  color: white;
  font-size: 18px;
  font-family: "Microsoft YaHei", sans-serif;
  /* text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); */
  font-weight: bold;
}
</style>
